#ifndef __M_FORMAT_H__
#define __M_FORMAT_H__
#include "mags.hpp"
#include "logs.hpp"
#include "unil.hpp"
#include <string>
#include <sstream>
#include <ctime>
#include <vector>
#include <thread>
#include <cassert>
using namespace std;

namespace TopLog
{
    // 抽象格式化基类
    class FormatItem
    {
    public:
        using ptr = shared_ptr<FormatItem>; // 智能指针 管理FormatItem内存文体
        virtual void format(ostream &out, const LogMsg &msg) = 0;
        virtual ~FormatItem() {}
    };
    // 派生：消息[%m]，等级[%p]，时间[%d]，文件名[%f]，行号[%l]
    // 线程id[%t]，日志器名[%c]，制表符[%T]，换行[%n]，其他

    // 多态实现，各类接口
    class MsgFormatItem : public FormatItem
    {
    public:
        MsgFormatItem(const string &str = "") {}
        void format(ostream &out, const LogMsg &msg) override
        {
            out << msg._payload;
        }
    };

    class LogsFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << Logs::Tostring(msg._logs); // 需要转换
        }
    };

    /*
        size_t strftime(char *s, size_t max, const char *format,const struct tm *tm);
        {%d{%H:%M:%S}}

        struct tm {
            //    int tm_sec;         /* seconds */
    //    int tm_min;         /* minutes */
    //    int tm_hour;        /* hours */
    //    int tm_mday;        /* day of the month */
    //    int tm_mon;         /* month */
    //    int tm_year;        /* year */
    //    int tm_wday;        /* day of the week */
    //    int tm_yday;        /* day in the year */
    //    int tm_isdst;       /* daylight saving time */
    //    };

    // struct tm *localtime_r(const time_t *timep, struct tm *result);

    // */

    class TimeFormatItem : public FormatItem
    {
    public:
        TimeFormatItem(const string &fmt = "%H:%M:%S")
            : _time_fmt(fmt)
        {
            if (_time_fmt.empty())
                _time_fmt = "%H:%M:%S";
        }
        void format(ostream &out, const LogMsg &msg) override
        {
            struct tm tp;
            localtime_r(&msg._ctime, &tp); // 转成结构体
            char arr[32] = {0};
            strftime(arr, 32, _time_fmt.c_str(), &tp); // 结构体-> str -> arr
            out << arr;
        }

    private:
        string _time_fmt;
    };

    class ThreadFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << msg._tid;
        }
    };

    class FileFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << msg._file;
        }
    };

    class LineFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << msg._line;
        }
    };

    class NameFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << msg._name;
        }
    };

    class TapFormatItem : public FormatItem //
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem
    {
    public:
        void format(ostream &out, const LogMsg &msg) override
        {
            out << "\n";
        }
    };

    class OrderFormatItem : public FormatItem
    {
    public:
        OrderFormatItem(const string &str)
            : _str(str) {}
        // gta[]
        void format(ostream &out, const LogMsg &msg) override
        {
            out << _str;
        }

    private:
        string _str;
    };

    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        //[222:1:1][root][321][logs.hpp:100][FATAL]创建套接字失败
        // 派生：消息[%m]，等级[%p]，时间[%d]，文件名[%f]，行号[%l]
        // 线程id[%t]，日志器名[%c]，制表符[%T]，换行[%n]，其他
        Formatter(const string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(passpattern());
        }
        // 对msg进行格式化
        void format(ostream &out, const LogMsg &msg)
        {
            for (auto &it : _item)
            {
                it->format(out, msg);
            }
        }
        string format(const LogMsg &msg)
        {
            stringstream ss;
            format(ss, msg); // 把ss作为输入流传入
            return ss.str();
        }

    private:
        // 1.处理其他字串
        // 2.处理%格式化字符，处理%%格式化字符
        // 3。处理{}子格式字符串

        // 对格式化规则字符串进行解析
        bool passpattern()
        {

            vector<pair<string, string>> fmt_order; // 存放格式化字符

            int pos = 0;
            string key, val; // 不需要清空
            while (pos < _pattern.size())
            {

                // 1.处理原始字串    abcd
                if (_pattern[pos] != '%')
                {
                    val.push_back(_pattern[pos++]);
                    continue;
                }

                //%%情况
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back('%');
                    pos += 2;
                    continue;
                }

                // 处理%x的方法
                if (val.empty() == false)
                {
                    fmt_order.push_back(make_pair("", val));
                    val.clear();
                }

                pos += 1;

                if (pos == _pattern.size())
                {
                    cout << "没有对应的格式化字符" << endl;
                    return false;
                }

                key = _pattern[pos]; // 记录key

                pos += 1; // 指向pos后字符

                //%+格式
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1;
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos++]); //{%H:%M:%S}
                    }
                    if (_pattern[pos] == _pattern.size()) // 末尾跳出循环
                    {
                        cout << "{}匹配错误" << endl;
                        return false;
                    }
                    pos += 1; // 跳出"}"
                }

                fmt_order.push_back(make_pair(key, val));
                key.clear();
                val.clear();
            }

            for (auto &it : fmt_order)
            {
                _item.push_back(createItem(it.first, it.second));
            }
            return true;
        }

        // 派生：消息[%m]，等级[%p]，时间[%d]，文件名[%f]，行号[%l]，
        // 线程id[%t]，日志器名[%c]，制表符[%T]，换行[%n]，其他
        //[%d{%H:%M:%S}[%t][%f:%l][%p]%T%m%n]

        // 根据字符格式调用派生类

        FormatItem::ptr createItem(const string &key, const string &val)
        {
            if (key == "d")
                return make_shared<TimeFormatItem>(val);
            if (key == "t")
                return make_shared<ThreadFormatItem>();
            if (key == "c")
                return make_shared<NameFormatItem>();
            if (key == "f")
                return make_shared<FileFormatItem>();
            if (key == "l")
                return make_shared<LineFormatItem>();
            if (key == "p")
                return make_shared<LogsFormatItem>();
            if (key == "T")
                return make_shared<TapFormatItem>();
            if (key == "m")
                return make_shared<MsgFormatItem>();
            if (key == "n")
                return make_shared<NLineFormatItem>();
            if (key.empty())
                return make_shared<OrderFormatItem>(val);
            cout << "没有匹配的格式化字符" << key << endl;
            abort();
            return FormatItem::ptr();
        }

    private:
        string _pattern; // 格式化规则字符串
        vector<FormatItem::ptr> _item;
    };
}

#endif